<!-- setup 无法设置组件名称，组件名称keepAlive必须 -->
<script lang="ts">
  export default {
    name: 'goods',
  };
</script>

<template>
  <div class="app-container">
    <el-form ref="queryForm" :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Position" @click="handleAdd">发布商品</el-button>
        <el-button type="danger" :icon="Delete" @click="handleDelete" :disabled="multiple">删除</el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.name" placeholder="商品名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-cascader
          v-model="queryParams.categoryId"
          placeholder="商品分类"
          :props="{ emitPath: false }"
          :options="categoryOptions"
          clearable
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      border
      style="width: 100%"
      :row-key="rowKey"
      :expand-row-keys="state.expandRowKeys"
      @expand-change="expandChange"
    >
      <el-table-column type="selection" align="center" min-width="5%"/>
      <el-table-column type="expand" label="库存" align="center" min-width="10%">
        <template #default="props">
          <el-table :data="props.row.skuList" border style="width: 100%">
            <el-table-column label="编码" prop="code" align="center" min-width="15%"/>
            <el-table-column label="名称" prop="name" align="center" min-width="25%"/>
            <el-table-column label="图片" prop="picUrl" align="center" min-width="30%">
              <template #default="scope">
                <el-popover placement="right" :width="400" trigger="hover">
                  <img :src="scope.row.picUrl" width="400" height="400"/>
                  <template #reference>
                    <img :src="scope.row.picUrl" style="max-height: 60px; max-width: 60px"/>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="现价" prop="price" align="center" min-width="10%">
              <template #default="scope">
                {{moneyFormatter(scope.row.price)}}
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stockQuantity" align="center" min-width="10%"/>
            <el-table-column label="操作" align="center" min-width="10%">
              <template #default="scope">
                <el-button
                  type="primary"
                  :icon="Edit"
                  circle
                  plain
                  @click.stop="handleUpdateSku(scope.row)"
                />
                <el-button
                  type="danger"
                  :icon="Delete"
                  circle
                  plain
                  @click.stop="handleDeleteSku(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="center" min-width="10%"/>
      <el-table-column label="图片" align="center" min-width="15%">
        <template #default="scope">
          <el-popover placement="right" :width="400" trigger="hover">
            <img :src="scope.row.picUrl" width="400" height="400"/>
            <template #reference>
              <img :src="scope.row.picUrl" style="max-height: 60px; max-width: 60px"/>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="类目" prop="categoryName" align="center" min-width="10%"/>
      <el-table-column label="品牌" prop="brandName" align="center" min-width="10%"/>
      <el-table-column label="零售价" prop="originalPrice" align="center" min-width="5%">
        <template #default="scope">
          {{moneyFormatter(scope.row.originPrice) }}
        </template>
      </el-table-column>
      <el-table-column label="促销价" prop="price" align="center" min-width="5%">
        <template #default="scope">{{
          moneyFormatter(scope.row.price)
          }}
        </template>
      </el-table-column>
      <el-table-column label="销量" prop="sales" align="center" min-width="5%"/>
      <el-table-column label="单位" prop="unit" align="center" min-width="5%"/>
      <el-table-column label="描述" prop="description" :show-overflow-tooltip="true" align="center" min-width="10%"/>
      <el-table-column label="详情" prop="detail" align="center" min-width="5%">
        <template #default="scope">
          <el-button
            type="primary"
            :icon="View"
            circle
            plain
            @click.stop="handleGoodsView(scope.row.detail)"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="state" align="center" min-width="5%">
        <template #default="scope">
          <el-switch
            v-model="scope.row.state"
            :inactive-value="false"
            :active-value="true"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="10%">
        <template #default="scope">
          <el-button
            type="primary"
            :icon="Edit"
            circle
            plain
            @click.stop="handleUpdate(scope.row)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            circle
            plain
            @click.stop="handleDelete(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页工具条 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.current"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <el-dialog v-model="dialogVisible" title="商品详情">
      <div class="goods-detail-box" v-html="goodDetail"/>
    </el-dialog>

    <!-- 表单弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      top="5vh"
      width="600px"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="编码" prop="code">
          <el-input v-model="formData.code" auto-complete="off"/>
        </el-form-item>

        <el-form-item label="商品规格" prop="name">
          <el-input v-model="formData.name"/>
        </el-form-item>

        <el-form-item label="图片" prop="logoUrl">
          <single-upload v-model="formData.picUrl"/>
        </el-form-item>

        <el-form-item label="现价" prop="price">
          <el-input v-model="formData.price"/>
        </el-form-item>

        <el-form-item label="库存" prop="stockQuantity">
          <el-input v-model="formData.stockQuantity"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSkuForm">确 定</el-button>
          <el-button @click="cancelUpdateSku">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
  import {reactive, ref, onMounted, toRefs} from 'vue';
  import {ElTable, ElMessage, ElMessageBox, ElForm} from 'element-plus';
  import {useRouter} from 'vue-router';
  import {Search, Position, Edit, Refresh, Delete, View} from '@element-plus/icons-vue';
  import {Dialog} from "@/types/common";
  import SingleUpload from '@/components/Upload/SingleUpload.vue';
  import {moneyFormatter} from '@/utils/filter';
  import {listCascadeCategories} from '@/api/pms/category';
  import {listPageGoods, deleteGoods, updateSpuState, getSkuFormDetail, updateSku, deleteSku} from '@/api/pms/goods';
  import {GoodsItem, GoodsQueryParam, SkuItem} from '@/types/api/pms/goods';


  const dataTableRef = ref(ElTable);
  const router = useRouter();
  const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
  const state = reactive({
    // 遮罩层
    loading: true,
    // 选中数组
    ids: [],
    // 非单个禁用
    single: true,
    // 非多个禁用
    multiple: true,
    total: 0,
    queryParams: {
      current: 1,
      pageSize: 10,
    } as GoodsQueryParam,
    goodsList: [] as GoodsItem[],
    categoryOptions: [],
    goodDetail: undefined,
    dialogVisible: false,
    dialog: {} as Dialog,
    formData: {sort: 1} as SkuItem,
    rules: {
      code: [
        {
          required: true,
          message: '请输入编码',
          trigger: 'blur',
        },
      ],
      name: [
        {
          required: true,
          message: '请输入商品规格',
          trigger: 'blur',
        },
      ],
      price: [
        {
          required: true,
          message: '请输入现价',
          trigger: 'blur',
        },
      ],
      stockQuantity: [
        {
          required: true,
          message: '请输入库存',
          trigger: 'blur',
        },
      ],
    },
    expandRowKeys: [],
  });
  const {
    loading,
    multiple,
    queryParams,
    goodsList,
    categoryOptions,
    goodDetail,
    total,
    dialogVisible,
    dialog,
    formData,
    rules,
    expandRowKeys,
  } = toRefs(state);


  function rowKey(row) {
    return row.id;
  }

  function handleQuery() {
    state.loading = true;
    listPageGoods(state.queryParams).then(({data}) => {
      state.goodsList = data.list;
      state.total = data.total;
      state.loading = false;
    });
  }

  function resetQuery() {
    state.queryParams = {
      current: 1,
      pageSize: 10,
      name: undefined,
      categoryId: undefined,
    };
    handleQuery();
  }

  function handleGoodsView(detail: any) {
    state.goodDetail = detail;
    state.dialogVisible = true;
  }

  function handleAdd() {
    router.push({path: 'goods-detail'});
  }

  function handleUpdate(row: any) {
    router.push({
      path: 'goods-detail',
      query: {goodsId: row.id, categoryId: row.categoryId},
    });
  }

  function handleDelete(row: any) {
    const ids = row.id || state.ids.join(',');
    ElMessageBox.confirm('是否确认删除选中的数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(function () {
        return deleteGoods(ids);
      })
      .then(() => {
        ElMessage.success('删除成功');
        handleQuery();
      });
  }

  /**
   * 状态修改
   */
  function handleStatusChange(row: any) {
    const text = row.state ? '上架' : '下架';
    ElMessageBox.confirm(
      '确认要' + text + '商品[' + row.name + ']吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        return updateSpuState(row.id, {state: row.state});
      })
      .then(() => {
        ElMessage.success(text + '成功');
      })
      .catch(() => {
        row.state = row.state === 'on' ? 'off' : 'on';
      });
  }

  function handleRowClick(row: any) {
    dataTableRef.value.toggleRowSelection(row);
  }

  function handleSelectionChange(selection: any) {
    state.ids = selection.map((item: { id: any }) => item.id);
    state.single = selection.length != 1;
    state.multiple = !selection.length;
  }

  function handleUpdateSku(row: any) {
    state.dialog = {
      title: '修改商品',
      visible: true,
    };
    const skuId = row.id || state.ids;
    getSkuFormDetail(skuId).then(({data}) => {
      state.formData = data;
      state.formData.price = (state.formData.price as any) / 100;
    });
  }

  /**
   * 取消
   */
  function cancelUpdateSku() {
    dataFormRef.value.resetFields();
    state.dialog.visible = false;
  }

  function handleDeleteSku(row: any) {
    const ids = row.id || state.ids.join(',');
    ElMessageBox.confirm('是否确认删除选中的数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(function () {
        return deleteSku(ids);
      })
      .then(() => {
        ElMessage.success('删除成功');
        handleQuery();
        expandRow(row.spuId);
      });
  }

  /**
   * 表单提交
   */
  function submitSkuForm() {
    dataFormRef.value.validate((isValid: boolean) => {
      if (isValid) {
        if (state.formData.id) {
          state.formData.price *= 100; // 金额转成分保存至数据库
          updateSku(state.formData.id, state.formData).then(() => {
            ElMessage.success('修改成功');
            cancelUpdateSku();
            handleQuery();
            expandRow(state.formData.spuId);
          });
        }
      }
    });
  }

  /**
   * 默认展示指定行
   */
  function expandRow(rowId) {
    //清空原有的展开行
    state.expandRowKeys = [];
    //展开当前行
    state.expandRowKeys.push(rowId)
  }

  /**
   * 关闭其他展开行
   * @param row
   * @param expandedRows
   */
  function expandChange(row, expandedRows) {
    if (expandedRows.length > 1) {
      dataTableRef.value.toggleRowExpansion(expandedRows[0])
    }
  }


  onMounted(() => {
    listCascadeCategories({}).then((response) => {
      state.categoryOptions = ref(response.data);
    });
    handleQuery();
  });
</script>

<style scoped></style>
